﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Utils
{
    public static class JsonHelper
    {
        private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
        {
            // 设置为驼峰命名
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            DateFormatString = "yyyy-MM-dd HH:mm:ss"
        };

        public static string ToJson(this object obj)
        {
            return obj == null ? null : JsonConvert.SerializeObject(obj, SerializerSettings);
        }

        public static T FromJson<T>(this string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return default;
            }

            try
            {
                return JsonConvert.DeserializeObject<T>(input);
            }
            catch (JsonException jsonEx)
            {
                Console.WriteLine($"JSON解析错误: {jsonEx.Message}");
                return default;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未知错误: {ex.Message}");
                return default;
            }
        }
    }
}